package com.allenkerr.rpc.common;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * RPC编码器
 * <p>
 * Created by 小柯(Allen Kerr) on 17.5.23 17:47.
 */
public class RpcEncoder extends MessageToByteEncoder {

    private Class<?> genericClass;

    //由构造函数传入需要序列化的class
    public RpcEncoder(Class<?> genericClass) {
        this.genericClass = genericClass;
    }

    //序列化操作
    @Override
    protected void encode(ChannelHandlerContext ctx, Object inObj, ByteBuf out) throws Exception {
        if (genericClass.isInstance(inObj)) {
            byte[] bytes = RpcSerializationUtils.serialize(inObj);
            out.writeInt(bytes.length);
            out.writeBytes(bytes);
        }
    }
}
